<?php
require_once('ActivityBase.class.php');

/**
 * +------------------------------------------------------------------------------
 * 用户活动关系表
 * +------------------------------------------------------------------------------
 * @property integer $id
 * @property integer $user_id
 * @property integer $activity_id
 * @property string $qr_code
 * @property string $post_path
 * @property string $post_media_id
 * @property integer $post_media_expire_time
 *
 * @property string $media
 * @property string $poster
 * @property ActivityModel $activity
 * @property JfUserModel $user
 *
 */
class UserActivityModel extends ActivityBase
{
    /**
     * @var ActivityModel $_activity 活动实例
     */
    protected $_activity;

    public function getActivity()
    {
        if (!$this->_activity) {
            $this->_activity = M('Activity');
            $this->_activity->find($this->activity_id);
        }

        return $this->_activity;
    }

    /** @var  string */
    protected $_poster;

    public function getPoster()
    {
        if (!$this->post_path) {
            $this->post_path = $this->generatePoster();
            $this->save();
        }

        return $this->post_path;
    }

    /** @var  JfUserModel */
    protected $_user;

    public function getUser()
    {
        if ($this->_user == null) {
            $this->_user = D('JfUser');
            $this->_user->find($this->user_id);
        }

        return $this->_user;
    }

    public function fields()
    {
        $a = parent::fields() ?: [];
        $array = array_merge($a, ['poster']);

        return $array;
    }


    /**
     * 生成海报
     */
    public function generatePoster()
    {
        $activity = $this->getActivity();
        if (!$activity) throw new Exception('活动没有找到');
        //获取活动海报设置
        $poster_params = $activity->poster_params;
        if (!$poster_params) throw new Exception('海报参数没有设置');

        $watermarkParams = json_decode($this->getActivity()->poster_params, true);
        $user = $this->getUser();
        $qrCode = $this->getQrCodePath();

        $content = function ($type) use ($user, $qrCode) {
            switch ($type) {
                case 'img':
                    $content = $user->pic;
                    break;
                case 'name':
                    $content = $user->username;
                    break;
                case 'qr';
                    $content = $qrCode;
                    break;
            }
            return $content;
        };

        foreach ($watermarkParams as &$watermarkParam) {
            $watermarkParam['x'] = (integer)$watermarkParam['x'] * 2;
            $watermarkParam['y'] = (integer)$watermarkParam['y'] * 2;
            $watermarkParam['w'] = (integer)$watermarkParam['w'] * 2;
            $watermarkParam['h'] = (integer)$watermarkParam['h'] * 2;
            $watermarkParam['content'] = $content($watermarkParam['type']);
        }


        $subPath = 'public/upload/images/' . date('Ym') . '/' . date('d') . '/';
        $imageRoot = RES_ROOT . $subPath;
        mkdir($imageRoot, 0777, true);
        $filename = $activity->id . '_post_' . $user->openid . '.jpg';

        $params = [
            'watermarkParams' => $watermarkParams,
            'activity' => $activity,
            'user' => $user,
            'savePath' => $imageRoot . $filename,
        ];

        /** @var MergeImageModel $model */
        $model = D('MergeImage');
        if ($model->generatePoster($params)) {
            return $subPath . $filename;
        } else {
            return false;
        }
    }

    public function getQrCodePath()
    {
        if (!$this->qr_code) {
            $model = new ImageGenerateModel();
            $this->qr_code = $model->generateQrcode($this->getUser(), $this->getActivity());
            $this->save();

        }
        return $this->qr_code;
    }

    /**
     * 回复海报
     */
    public function replyPost()
    {
        $wechat = WeChatApp::instance();
        return $wechat->image($this->media)->reply();
    }

    /**
     * @return string 返回media_id
     */
    public function getMedia()
    {
        if (!$this->post_media_id || $this->isExpire()) {
            $wechat = WeChatApp::instance();
            $response = $wechat->uploadMedia(RES_ROOT . $this->getPoster(), 'image');
            $media_id = $response['media_id'];
            $this->post_media_id = $media_id;
            $this->post_media_expire_time = 3600 * 24 * 3 + time();
            $this->save();
        }

        return $this->post_media_id;
    }

    /**
     * 微信临时素材是否过期
     * @return bool
     */
    protected function isExpire()
    {
        return time() - $this->post_media_expire_time > (3600 * 24 * 3);
    }

    /**
     * 发放上级的奖励
     * @return boolean
     */
    public function addAward()
    {
        $res = true;
        $activity = $this->getActivity();
        $awards = $activity->getParentsAward();
        $user = $this->getUser();
        foreach ($awards['content'] as $index => $content) {
            $parent = $user->getParent();
            $parent->setInc($awards['type'], $content);
        }

        return $res;
    }

    /**
     * 初次关注奖励
     * @return boolean
     */
    public function firstTimeFollowAward()
    {
        $activity = $this->getActivity();
        $awards = $activity->getFirstTimeFollowAward();
        $user = $this->getUser();

        return $user->setInc($awards['type'], $awards['content']);
    }

    /**
     * 关注时回复
     */
    public function replyWhenFollow()
    {
        $app = WeChatApp::instance();
        $app->sendCustomMessage([
            'touser' => $this->getUser()->openid,
            'msgtype' => 'text',
            'text' => [
                'content' => $this->getActivity()->first_time_follow_msg,
            ]
        ]);
    }

    /**
     * 点击生成海报参加活动
     * @param $activity_id
     * @param $open_id
     * @return $this
     * @throws Exception
     */
    public function joinActivity($activity_id, $open_id)
    {
        $activity = D('Activity');
        /** @var JfUserModel $user */
        $user = D('JfUser');
        $res = $user->where(['openid' => $open_id])->find();
        // 活动不存在
        if (!$activity->find($activity_id)) {
            throw new \Exception('活动不存在');
        }
		if(!$activity->where('start_date<='.time().' and end_date>='.time().' and id='.$activity_id)->find()){
			$app = WeChatApp::instance();
			$app->sendCustomMessage([
				'touser' => $open_id,
				'msgtype' => 'text',
				'text' => [
					'content' => '活动已经结束',
				]
			]);
			exit;
		}else{
			// 参与活动的新用户
			if (!$res) {
				$app = WeChatApp::instance();
				if (is_array($open_id)) {
					$weChatUser = $open_id;
				} else {
					$weChatUser = $app->getUserInfo($open_id);

				}

				$user->username = $weChatUser['nickname'];
				$user->pic = $weChatUser['headimgurl'];
				$user->openid = $weChatUser['openid'];
				$user->unionid = $weChatUser['unionid'] ?: '';
				$user->sex = $weChatUser['sex'];
				$user->follow_time = 1;
				$user->province = $weChatUser['province'];
				$user->city = $weChatUser['city'];
				$user->app_name = $app->getRevTo();
				$user->create_time = time();

				$user->add();
			}

			$res = $this->where(['user_id' => $user->id, 'activity_id' => $activity_id])->find();

			if (!$res) {
				// 参加活动
				$this->activity_id = $activity_id;
				$this->user_id = $user->id;
				$id = $this->add();
				$this->find($id);
			}

			return $this;
		}
        
    }


    /**
     * 扫描二维码参加活动
     * @param $activity_id
     * @param $weChatUser
     * @param $parent_open_id
     * @return $this
     * @throws Exception
     */
    public function joinActivityFrom($activity_id, $weChatUser, $parent_open_id)
    {
        /** @var ActivityModel $activity */
        $activity = D('Activity');
        /** @var JfUserModel $user */
        $user = D('JfUser');
        $app = WeChatApp::instance();

        // 活动不存在
        if (!$activity->find($activity_id)) {
            throw new \Exception('活动不存在');
        }
		if(!$activity->where('start_date<='.time().' and end_date>='.time().' and id='.$activity_id)->find()){
			$app = WeChatApp::instance();
			$app->sendCustomMessage([
				'touser' => $open_id,
				'msgtype' => 'text',
				'text' => [
					'content' => '活动已经结束',
				]
			]);
		}else{
			
			$user = D('JfUser');
			$res = $user->where(['unionid' => $weChatUser['unionid']])->find();

			// 参与活动的新用户
			if (!$res) {

				$parent = M('JfUser')->where(['openid' => $parent_open_id])->find();

				$user->parent_id = $parent['id'];
				$user->username = $weChatUser['nickname'];
	//            $user->pic = $weChatUser['headimgurl'];
				$user->openid = $parent_open_id ? '' : $weChatUser['openid'];
				$user->unionid = $weChatUser['unionid'] ?: '';
	//            $user->sex = $weChatUser['sex'];
				$user->follow_time = $parent_open_id ? 0 : 1;
	//            $user->province = $weChatUser['province'];
	//            $user->city = $weChatUser['city'];
				$user->app_name = $parent_open_id ? $parent['app_name'] : $app->getRevTo();
	//            $user->create_time = time();
				$user->create_time = time();
				$user->activity_id = $activity_id;

				$user_id = $user->add();
			} else {
				/*
				if(empty($res['parent_id'])){
					$p = M('JfUser')->where(['openid' => $parent_open_id])->find();
					$parentid = $p['id'];
					if($parentid != $res['id']){
						D('JfUser')->query('update tbl_jf_user set parent_id='.$parentid.' where id='.$res['id']);
					}					
				}
				*/
				$app->sendCustomMessage([
					'touser' => $user->openid,
					'msgtype' => 'text',
					'text' => [
						'content' => $activity->repeat_scan_msg,
					]
				]);
			}

			$res = $this->where(['user_id' => $user_id, 'activity_id' => $activity_id])->find();

			if (!$res) {
				// 参加活动
				$ua = D('UserActivity');
				$ua->activity_id = $activity_id;
				$ua->user_id = $user_id;
				$ua->add();

			}
			return $this;
		}
    }

}

?>